const easyMonitor = require('easy-monitor')
easyMonitor('Choice Server')

const Koa = require('koa')
const app = new Koa()
const path = require('path')
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const koaBody = require('koa-body')
const logger = require('koa-logger')
const util = require('./utils/util')

const index = require('./routes/index')
const users = require('./routes/users')
const auth = require('./routes/auth')
const paramter = require('./routes/parameter')
const recommend = require('./routes/recommend')
const analysis = require('./routes/analysis')

// const init = require('./init')

util.isDirExists(path.join(__dirname, 'public/uploads'))
process.env.PORT = '5000'
// error handler
onerror(app)

// middlewares
app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: path.join(__dirname, 'public/uploads'),
    keepExtensions: true
  }
}));
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`-------${start}-------`)
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(auth.routes(), auth.allowedMethods())
app.use(paramter.routes(), paramter.allowedMethods())
app.use(recommend.routes(), recommend.allowedMethods())
app.use(analysis.routes(), analysis.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

// init()

module.exports = app
